import React, { Component } from "react";

export default class Form2 extends Component {
  // 1. 声明状态
  state = {
    username: "",
    password: "",
    phone: ''
  };

  render() {
    let res = this.saveData('username')
    return (
      <div>
        <h2>登录</h2>
        {/* 2. 设置input元素的 value 为 state 中的值 */}
        {/* 3-1. 为 input 元素设置 onChange 回调 */}
        用户名:{" "}
        <input
          type="text"
          value={this.state.username}
          onChange={res}
        />
        <br></br>
        密码:{" "}
        <input
          type="password"
          value={this.state.password}
          onChange={this.saveData('password')}
        /><br />
        手机号: <input
          type="text"
          value={this.state.phone}
          onChange={this.saveData('phone')}
        />
        <br />
        <button onClick={this.login}>登录</button>
        <button onClick={this.reset}>清空</button>
      </div>
    );
  }

  //3-2 用户名元素丧失焦点事件回调
  saveData = (type) => {
    return (e) => {
      //执行 setState
      this.setState({
        [type] : e.target.value
      })
    }
  };


  //登录按钮的点击回调
  login = () => {
    //获取用户名
    // console.log(this.state.username);
    console.log(
      `用户名为 ${this.state.username} , 密码为 ${this.state.password}`
    );
  };

  //表单重置
  reset = () => {
    //清空用户名
    this.setState({
      username: "",
      password: ''
    });
  };
}
